package com.sxt.server;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 服务器程序
 */
public class TCPServer implements Runnable {

	private static ServerSocket server = null; // 服务器
	private static Socket client = null; // 客户端
	private static List<Socket> clients = null;

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		clients = new ArrayList<Socket>();
		try {
			server = new ServerSocket(8888);
			System.out.println("服务器已启动...");
			while (true) {
				/*
				 * 接收客户端请求
				 */
				client = server.accept();
				clients.add(client);
				System.out.println("一个客户端已连接...");
				new Thread(new TCPServer(), "消息处理").start();
			}
		} catch (IOException e) {
			System.out.println("端口被占用！");
		} finally {
			try {
				if (server != null) {
					server.close();
				}
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}

	}

	@Override
	public void run() {
		BufferedReader br = null; // 接收消息管道
		String str = null; // 发送消息管道
		PrintWriter pw = null; // 消息内容
		try {
			br = new BufferedReader(new InputStreamReader(
					client.getInputStream()));
			/*
			 * 接收客户端发送的消息
			 */
			while ((str = br.readLine()) != null) {
				System.out.println(client.getInetAddress().getHostAddress()
						+ "-->" + str);

				/*
				 * 将接收到的信息发送给客户端
				 */
				for (Socket currentClient : clients) {
					pw = new PrintWriter(currentClient.getOutputStream());
					pw.println(new SimpleDateFormat("yyyy年mm月dd日 HH:mm:ss")
							.format(new Date()) + "\n" + str);
					pw.flush();
				}
			}
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}
